package threads;

import java.util.Observable;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import data.Page;
import data.STATUS;
/**
 * 
 * @author Dan Dalton
 * @author Gavin Greene
 * 
 * Fetches a webpage from a given URL.
 *
 */
public class Fetcher extends Observable implements Runnable, Comparable{
	/**
	 * Page that will be fetched.
	 */
	private final Page my_page;
	
	/**
	 * Fetches a page using the URL from the Page.
	 * @param the_page to be fetched.
	 */
	public Fetcher(final Page the_page){
		my_page = the_page;
	}

	@Override
	public void run() {
		final long start = System.currentTimeMillis();
		try{
			System.out.println(my_page.getUrl());
			//Connection c = Jsoup.connect(my_page.getUrl());
			Document doc = Jsoup.connect(my_page.getUrl()).get();
			final long end = System.currentTimeMillis();
			final long runtime = end - start;
			// Updating status with the fetched doc and runtime.
			my_page.setStatus(STATUS.FETCHED, doc, runtime);
			finish();
		} catch (Exception e){
			System.out.println("JSOUP Choked on this URL: " + my_page.getUrl());
			System.out.println(e);
			finish();
		}
	}
	
	/**
	 * Announces to the world that you've finished like a boss.
	 */
	private void finish(){
		this.setChanged();
		this.notifyObservers(my_page);
	}
	/**
	 * Gets my page.
	 * @return the page I'm working on.
	 */
	public Page getPage(){
		return my_page;
	}
	
	@Override
	public int compareTo(Object arg0) {
		//TODO: For some reason the TPE throws a fit if these aren't comparable?
		// This horrible workaround seems to have no negative effect... 
		return 1;
	}
}
